<template>
  <a-card :bordered="false">
    <div class="table-operator">
      <a-button v-if="hasPerm('Cust_Communication.Add')" type="primary" icon="plus" @click="handleAdd()">新建</a-button>
      <a-button type="primary" icon="redo" @click="getDataList()">刷新</a-button>
    </div>
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="10">
          <a-col :md="4" :sm="24">
            <a-form-item label="查询类别">
              <a-select showArrow v-model="queryParam.Conditions[0].condition" @change="handleQueryParamChange">
                <a-select-option key="DRKeyWord">关键字</a-select-option>
                <a-select-option key="DailyRecordTitle">标题</a-select-option>
                <a-select-option key="DailyRecord">沟通内容</a-select-option>
                <a-select-option key="CustomerName">客户名称</a-select-option>
                <a-select-option key="SharerIds">抄送人</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="24">
            <a-form-item>
              <a-input allowClear v-if="IsShowing" @keydown="inputKeyDown" v-model="queryParam.Conditions[0].keyword" :placeholder="this.inputKeyWords"/>
              <a-select
                show-search
                allowClear
                v-if="!IsShowing"
                :v-model="queryParam.Conditions[0].keyword===''?this.inputKeyWords:queryParam.Conditions[0].keyword"
                :placeholder="this.inputKeyWords"
                :default-active-first-option="false"
                :show-arrow="false"
                :filter-option="false"
                @search="handleShareIdsSearch"
                @change="handleShareIdsChange"
              >
                <a-select-option v-for="d in searchdata" :key="d.Id" :value="d.Id">
                  {{ d.RealName }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="24">
            <a-form-item>
              <a-range-picker @change="rangechange" v-model="time" :allowClear="false"/>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-button
              type="primary"
              @click="
                () => {
                  this.pagination.current = 1
                  this.getDataList()
                }
              "
            >查询
            </a-button
            >
            <a-button style="margin-left: 8px" @click="reset">重置</a-button>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <a-spin :spinning="loading">
      <div class="timelineScroll" :style="timelineScrollHeight">
        <a-list item-layout="vertical" size="large" :pagination="false" :data-source="data">
          <a-list-item slot="renderItem" key="item.title" slot-scope="item, index">
            <template slot="actions" v-if="CreatorId == item.CreatorId">
              <span @click="modalShow(item)"><a>抄送</a></span>
              <span @click="handleEdit(item, '编辑')"><a>编辑</a></span>
              <span @click="handleEdit(item)"><a>查看</a></span>
            </template>
            <template slot="actions" v-if="CreatorId == item.CreatorId && item.SDRDTOList.length > 0">
              <a-tooltip>
                <template slot="title">
                  <p
                    v-for="(val, ind) in item.SDRDTOList"
                    :key="ind"
                    style="cursor: pointer;"
                    @click="openUrl(val.FileURL)"
                  >
                    {{ val.FileURL ? val.FileURL.substring(val.FileURL.lastIndexOf('/') + 1) : '' }}
                  </p>
                </template>
                <span><a>附件</a></span>
              </a-tooltip>
            </template>
            <template slot="actions" v-if="CreatorId != item.CreatorId">
              <span @click="handleEdit(item)"><a>查看</a></span>
            </template>
            <template slot="actions">
              <span>
                <a-tag v-for="(im, index) in item.SharerNameList" :key="index">{{ im }}</a-tag></span
              >
            </template>
            <a-list-item-meta :description="item.CustomerName">
              <b slot="title">
                <span class="recordtitle">{{ moment(item.DailyRecordDate).format('YYYY-MM-DD HH:mm:ss') }}</span>
                <span class="datetime">
                  <span>{{ item.DailyRecordTitle }}</span>
                  <span style="margin-left: 12px; color: #333">{{ item.SalesmanName }}</span>
                </span>
              </b>
            </a-list-item-meta>
            <span class="content" v-html="item.DailyRecord"></span>
          </a-list-item>
        </a-list>
      </div>
      <div style="text-align: right;margin-top: 24px">
        <a-pagination
          v-show="pagination.total"
          @change="handleChange"
          :total="pagination.total"
          :pageSize="pagination.pageSize"
          show-size-changer
          @showSizeChange="handleSizeChange"
          :show-total="total => `总数: ${pagination.total}`"
        />
      </div>
    </a-spin>
    <a-modal
      title="人员通知"
      :visible="modalVisible"
      :confirm-loading="modalLoading"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-select
        allowClear
        v-model="selectedUser"
        mode="multiple"
        :filter-option="filterOption"
        style="width: 100%"
        placeholder="请选择要通知的人员">
        <a-select-option v-for="item in userList" :key="item.Id">
          {{ item.RealName }}
        </a-select-option>
      </a-select>
    </a-modal>
    <edit-form ref="editForm" :parentObj="this"></edit-form>
  </a-card>
</template>

<script>
import OperatorCache from '@/utils/cache/OperatorCache'
import EditForm from '@/views/CustomerManagement/MyCustomer/CommunicationForm.vue'
import moment from 'moment'

export default {
  components: {
    EditForm
  },
  computed: {
    timelineScrollHeight () {
      return {
        maxHeight: this.tableHeight + 'px'
      }
    }
  },
  mounted () {
    this.CreatorId = this.op().Id
    this.getDataList()
    this.getUserList()
  },
  data () {
    return {
      actionslist: [],
      data: [],
      tableHeight: 570, // 表格高度
      pagination: {
        current: 1,
        pageSize: 20,
        showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
        pageSizeOptions: ['20', '30', '40', '50', '100'], // 设置pageSize的可选值，页面可以通过下拉框进行选择
        showSizeChanger: true
      },
      filters: {},
      sorter: { field: 'DailyRecordDate', order: 'desc' },
      loading: false,
      time: [],
      queryParam: {
        sDate: '',
        dDate: '',
        Conditions: [
          {
            condition: 'DRKeyWord',
            keyword: ''
          }
        ]
      },
      IsShowing: true,
      inputKeyWords: '请输入关键字信息',
      selectedRowKeys: [],
      modalVisible: false,
      modalLoading: false,
      selectedUser: [],
      searchdata: [],
      userList: [],
      moment,
      recordId: '',
      userobj: {},
      CreatorId: ''
    }
  },
  methods: {
    rangechange (time) {
      console.log(moment(moment(time[0]).format('YYYY-MM-DD 00:00:00')))
      console.log(moment(time[1]))
      this.queryParam.sDate = moment(time[0]).format('YYYY-MM-DD 00:00:00')
      this.queryParam.dDate = moment(time[1]).format('YYYY-MM-DD 23:59:59')
    },
    openUrl (url) {
      window.open(url)
    },
    inputKeyDown (e) {
      if (e.keyCode === 13) {
        if (!this.queryParam[0].keyword) return this.$message.error('请输入查询条件')
        this.getDataList()
      }
    },
    reset () {
      this.time = []
      this.IsShowing = true
      this.inputKeyWords = '请输入关键字'
      this.queryParam = {
        sDate: '',
        dDate: '',
        Conditions: [
          {
            condition: 'DRKeyWord',
            keyword: ''
          }
        ]
      }
    },
    op () {
      return OperatorCache.info
    },
    filterOption (input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    modalShow (record) {
      if (record.SharerIds) this.selectedUser = record.SharerIds.split('|')
      this.modalVisible = true
      this.recordId = record.Id
    },
    handleOk () {
      if (this.selectedUser.length <= 0) return this.$message.error('请选择分享人')
      this.$http
        .post('/CustomerManagement/SalesmanDailyRecord/UpdateDataByCondition', {
          Conditions: [
            {
              Condition: 'SharerIds',
              Keyword: this.selectedUser.join('|')
            }
          ],
          ids: [this.recordId]
        })
        .then(res => {
          if (res.Success) {
            this.getDataList()
            this.$message.success('操作成功')
          } else {
            this.$message.error(res.Msg)
          }
          this.modalVisible = false
        })
    },
    handleCancel () {
      this.modalVisible = false
      this.selectedUser = []
    },
    handleChange (page, pageSize) {
      this.pagination.current = page
      this.getDataList()
    },
    handleSizeChange (current, size) {
      this.pagination.current = 1
      this.pagination.pageSize = size
      this.getDataList()
    },
    detail (content) {
      this.title = content.DailyRecordTitle
      this.content = content.DailyRecord
      this.visible = true
    },
    getUserList () {
      this.$http
        .post('/Base_Manage/Base_User/GetDataList', {
          PageIndex: 1,
          PageRows: 999,
          SortField: 'CreateTime',
          SortType: 'desc',
          Search: {}
        })
        .then(resJson => {
          this.loading = false
          this.userList = resJson.Data
          this.userobj = {}
          this.userList.forEach(item => {
            this.userobj[item.Id] = item.RealName
          })
        })
    },
    getDataList () {
      this.loading = true
      this.$http
        .post('/CustomerManagement/SalesmanDailyRecord/GetDataListByMySelfAndMoreCondition', {
          PageIndex: this.pagination.current,
          PageRows: this.pagination.pageSize,
          SortField: 'DailyRecordDate',
          SortType: 'desc',
          Search: this.queryParam
        })
        .then(res => {
          this.loading = false
          if (res.Success) {
            this.data = res.Data
            this.pagination.total = res.Total
          }
        })
    },
    handleAdd () {
      this.$refs.editForm.openForm(null, '新建沟通记录')
    },
    handleEdit (record, title) {
      let str = '沟通记录查看'
      if (title === '编辑') str = '沟通记录编辑'
      this.$refs.editForm.openForm(record, str)
    },
    // 条件选择
    handleQueryParamChange (value, option) {
      this.IsShowing = true
      if (option.key === 'DRKeyWord') {
        this.inputKeyWords = '请输入关键字'
      }
      if (option.key === 'DailyRecordTitle') {
        this.inputKeyWords = '请输入标题信息'
      }
      if (option.key === 'DailyRecord') {
        this.inputKeyWords = '请输入沟通内容'
      }
      if (option.key === 'CustomerName') {
        this.inputKeyWords = '请输入客户名称'
      }
      if (option.key === 'SharerIds') {
        this.inputKeyWords = '请选择抄送人'
        this.IsShowing = false
      }
    },
    // 远程搜索用户信息
    handleShareIdsSearch (keyword) {
      if (keyword) {
        this.getShareIdsSearch(keyword)
      } else {
        this.searchdata = []
      }
    },
    handleShareIdsChange (id) {
      var obj = this.searchdata.find(val => {
        return val.Id === id
      })
      this.queryParam.Conditions[0].keyword = id
    },
    // 查询用户信息
    getShareIdsSearch (keyword) {
      this.$http.post('/Base_Manage/Base_User/GetDataListAsyncByCondition', {
        PageIndex: 1,
        SortField: 'CreateTime',
        SortType: 'desc',
        Search: { Condition: 'RealName', Keyword: keyword }
      }).then(resJson => {
        if (resJson.Success) {
          this.searchdata = resJson.Data
        } else {
          this.$message.error(resJson.Msg)
          this.searchdata = []
        }
      })
    }
  }
}
</script>
<style scoped>
.recordtitle {
  font-weight: normal;
  color: rgba(0, 0, 0, 0.45);
  font-size: 20px;
}

.datetime {
  margin-left: 8px;
  font-weight: normal;
  color: rgba(0, 0, 0, 0.45);
  font-size: 14px;
}

.timelineScroll {
  /*max-height: 570px;*/
  overflow-y: scroll;
}

.timelineScroll::-webkit-scrollbar {
  height: 5px;
  width: 5px;
}

.timelineScroll::-webkit-scrollbar-thumb {
  /* 滚动条里面小方块 */
  border-radius: 10px;
  -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  background: #acacac;
}

.timelineScroll::-webkit-scrollbar-track {
  /* 滚动条里面轨道 */
  -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  border-radius: 10px;
  background: #ededed;
}

.content {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 5;
  overflow: hidden;
}
</style>
